package org

import (
	//"errors"
	"dhfshop/models/isv"
	"encoding/json"
	"github.com/astaxie/beego"
	"dhfshop/service/redisgo"
)

type OnlineAgent struct {
	AgentId      int64   `json:"agent_id"`      //客服工号
	Account      string  `json:"account"`       //完整客服账号
	Status       int     `json:"status"`        //客服在线状态：1：pc在线; 2:手机在线; 3: pc和手机同时在线则：1+2=3
	AutoAccept   int     `json:"auto_accept"`   //客服设置最大自动接入数
	AcceptedCase int     `json:"accepted_case"` //客服当前正在接待的会话数
}

type MsgCacheUser struct {
	AppId         string            `json:"app_id"`
	PartnerId     int64             `json:"partner_id"`
    ServiceTypeId int               `json:"service_type_id"`  //公众号类型，1公共号，2小程序
	VerifyTypeId  int               `json:"verify_type_id"`   //认证类型，-1代表未认证，0代表微信认证(认证后可以使用微信多客服系统)
	RoleIds       []int64           `json:"role_ids"`
	OpenIdUserId  map[string]int64  `json:"openid_userid"`
	OnlineAgents  []*OnlineAgent    `json:"online_agents"`    //多客服新扩展字段
}

func GetCacheServiceUser(appId string) (*MsgCacheUser, error) {
	var msgUser *MsgCacheUser = new(MsgCacheUser)
	cacheKey := appId
    redisconn := redisgo.GetInstance()
	if cacheValue, err := redisconn.GetString(cacheKey); err == nil && len(cacheValue) > 20  {
	    //beego.Debug("msg cache user", cacheValue)
		if err = json.Unmarshal([]byte(cacheValue), msgUser); err == nil {
			return msgUser, nil
		}
	}
	if msgUser.PartnerId == 0 {
	    custAccount, err := isv.GetCustAccountByAppId(appId)
		if err != nil {
		    return nil, err
		}
		roleIds, err := GetRoleIdsByPartnerIdAndSet(custAccount.PartnerId, 1)
		if err != nil {
		    return nil, err
		}
		msgUser.AppId   = appId
		msgUser.PartnerId = custAccount.PartnerId
		msgUser.ServiceTypeId = custAccount.ServiceTypeId
		msgUser.VerifyTypeId = custAccount.VerifyTypeId
		msgUser.RoleIds = roleIds
		msgUser.OpenIdUserId = make(map[string]int64)
		for _, roleId := range roleIds {
			if users, err := GetSubUsers(roleId, 0, 50); err == nil {
			    for _, user := range users {
				   msgUser.OpenIdUserId[user.OpenID] = user.UserId
				}
			}
		}
		//if len(msgUser.OpenIdUserId) == 0 {
		//    return nil, errors.New("Error: no valid message receiver")
		//}
		if userJSON, err := json.Marshal(msgUser); err == nil {
		    //beego.Debug("userJSON", string(userJSON))
			if _, err = redisconn.Set(cacheKey, string(userJSON), 1*3600); err != nil {  //1个小时过期,解决权限过期的问题
			    beego.Debug("SETEX", err.Error())
			}
	    }
	}
	return msgUser, nil
}

